package com.ffapp.f9164.td.query;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.clj.fastble.utils.BleLog;
import com.ffapp.f9164.td.R;
import com.ffapp.f9164.td.bean.ParamListData;
import com.ffapp.f9164.td.eventbus.PopHandleMessage;
import com.ffapp.f9164.td.home.HomeBaseActivity;
import com.ffapp.f9164.td.util.SubstringUtil;
import com.suke.widget.SwitchButton;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.MySharedPreferences;

public class QueryIndexActivity extends HomeBaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> queryList;
    private boolean isOnPause = false;
    private boolean isContinuRefresh = false;
    MySharedPreferences mSp ;

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.activity_query);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);

        setTitleRightButton(R.mipmap.refresh, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!mSp.getDevType().equals("F-CD100")){
                    showToast("此设备不支持该功能");
                    return;
                }
                isContinuRefresh= false;
                isOnPause = true;
                showProgress();
                sendAtSearch();
            }
        });
        setTitleLeftText("查询信息",Color.WHITE,null);
        mSp = new MySharedPreferences(mContext);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        queryList = new ArrayList<>();
    }
    private void sendAtSearch(){
            BleUtils.sendAtSearchOrTakePicture(false,new BleUtils.BleUtilCallBack() {
                @Override
                public void onWriteFailure(String message) {
                    showToast(message);
                    dismissProgress();
                }

                @Override
                public void onSuccess(String message) {
                    dismissProgress();
                    showToast(message);
                }

                @Override
                public void onError(String message) {
                    showToast(message);
                    dismissProgress();
                }

                @Override
                public void onResult(StringBuffer message) {
                    setList(message.toString());
                    dismissProgress();
                    if(!isOnPause){
                        handler.postDelayed(runnable, 5000);
                    }
                }
                @Override
                public void onByte(byte[] bytes) {

                }
            });
    }

    public void setList(String sMsgObjString) {
        if (isFinishing()){
            return;
        }
        queryList.clear();
        if (!TextUtils.isEmpty(sMsgObjString)) {
            //信号强度
            String sysCSQ = SubstringUtil.subString(sMsgObjString, "SysCSQ:");
            queryList.add(new ParamListData("信号强度", 2, ""+sysCSQ, "", ""));

            //GPRS状态
            String gprsSt = SubstringUtil.subString(sMsgObjString, "GprsSt:");
            switch (gprsSt){
                case "0":
                    gprsSt = "网络开始状态";
                    break;
                case "1":
                    gprsSt = "网络初始化状态";
                    break;
                case "2":
                    gprsSt = "网络待机状态（4G模块只使用短信时使用）";
                    break;
                case "3":
                    gprsSt = "网络连接状态（LORA及北斗使用）";
                    break;
                case "4":
                    gprsSt = "网络连接成功状态（LORA及北斗使用）";
                    break;
                case "5":
                    gprsSt = "网络拨号状态";
                    break;
                case "6":
                    gprsSt = "网络拨号成功状态";
                    break;
                case "7":
                    gprsSt = "网络关闭状态";
                    break;
                case "8":
                    gprsSt = "网络停止状态";
                    break;
                case "9":
                    gprsSt = "网络未处理状态";
                    break;
            }
            queryList.add(new ParamListData("信号强度", 2,""+ gprsSt, "", ""));

            //电池电压
            String batVolt = SubstringUtil.subString(sMsgObjString, "BatVolt:");
            queryList.add(new ParamListData("电池电压", 2, ""+batVolt, "", "伏"));

            //设备温度
            String devTemp = SubstringUtil.subString(sMsgObjString, "DevTemp:");
            queryList.add(new ParamListData("设备温度", 2, ""+devTemp, "", "度"));

            //水位
            String curWaterLevel = SubstringUtil.subString(sMsgObjString, "CurWaterLevel:");
            queryList.add(new ParamListData("水位", 2, ""+curWaterLevel, "", "米"));

            //瞬时流量
            String curFlow = SubstringUtil.subString(sMsgObjString, "CurFlow:");
            queryList.add(new ParamListData("瞬时流量", 2, ""+curFlow, "", "立方米每秒"));

            //Socket1 Socket2 Socket3 Socket4状态
            String centerSt = SubstringUtil.subString(sMsgObjString, "CenterSt:");
            String[] centerSts = centerSt.split(",");
            for (int i = 0; i<centerSts.length; i++){
                String value = "";
                switch (centerSts[i]){
                    case "0":
                        value = "无";
                        break;
                    case "1":
                        value = "开始状态";
                        break;
                    case "2":
                        value = "初始状态";
                        break;
                    case "3":
                        value = "解析域名等待";
                        break;
                    case "4":
                        value = "解析域名中";
                        break;
                    case "5":
                        value = "创建实例";
                        break;
                    case "6":
                        value = "连接中";
                        break;
                    case "7":
                        value = "连接成功后等待";
                        break;
                    case "8":
                        value = "连接成功";
                        break;
                    case "9":
                        value = "NB连接成功";
                        break;
                    case "10":
                        value = "连接关闭";
                        break;
                    case "11":
                        value = "连接停止";
                        break;
                }
                queryList.add(new ParamListData("Socket"+(i+1)+"状态", 2, ""+value, "", ""));
            }

            //定时采集间隔
            String sampleInt = SubstringUtil.subString(sMsgObjString, "SampleInt:");
            queryList.add(new ParamListData("定时采集间隔", 2, ""+sampleInt, "", "分"));

            //定时上报间隔
            String reportInt = SubstringUtil.subString(sMsgObjString, "Report Int:");
            queryList.add(new ParamListData("定时上报间隔", 2, ""+reportInt, "", "分"));

        }
        adapter.notifyDataSetChanged();
//        recyclerView.setAdapter(adapter);
    }
    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_terminal_item, viewGroup, false);
            return new MyAdapter.ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return queryList == null ? 0 : queryList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                ParamListData queryListData = queryList.get(position);
                tvName.setText(queryListData.getName());
                editText.setText("" + queryListData.getValue());
                tvUnit.setVisibility(View.VISIBLE);
                tvUnit.setText(queryListData.getUnit());
                imgSpanner.setVisibility(View.GONE);
                switchBtn.setVisibility(View.GONE);
                editText.setEnabled(false);//可编辑
                list_item.setBackgroundResource(R.color.white);
            }
        }
    }


    private Handler handler = new Handler();
    private Runnable runnable  = new Runnable(){//推送runnable，定期2s执行一次
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Log.d("QueryIndexActivity","runnable");
            if(!isOnPause){
                sendAtSearch();
            }
        }
    };


    @OnClick(R.id.btn_update)
    public void update(){
        if(!mSp.getDevType().equals("F-CD100")){
            showToast("此设备不支持该功能");
            return;
        }
        if(isContinuRefresh){
            showToast("已持续更新，请勿重复点击");
            return;
        }
        handler.post(runnable);//定期执行
        isOnPause = false;
        isContinuRefresh = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private boolean isFront = false;

    @Override
    protected void onResume() {
        super.onResume();
        isFront = true;
    }

    @Override
    protected void onPause() {
        BleUtils.stopNotify();
        isFront = false;
        isOnPause = true;
        isContinuRefresh = false;
        super.onPause();
    }

    @Override
    public void onMessageEvent(PopHandleMessage event) {
        super.onMessageEvent(event);
        if(isFront ){
            BleUtils.reConnect(mContext, new BleUtils.BleUtilLoginCallBack() {
                @Override
                public void isLogin(boolean isSuccess,String message) {
                    showToast(""+message);
                    dismissProgress();
                }
            });
        }
    }
}
